﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Services.Protocols;
using System.Windows.Forms;
using OrbitOne.CRMUpdater.CRM;

namespace OrbitOne.CRMUpdater
{
    public partial class frmLoginScreen : Form
    {
        #region Private variables
        private Updator upd;
        private Timer timer = null;
        private List<Connection> connections;
        #endregion

        #region Constructor
        public frmLoginScreen()
        {
            InitializeComponent();
            ddlAuth.Items.AddRange(new object[] { "Active Directory", "Passport", "On Premise" });
            connections = Connection.Load();
            dllLabel.DisplayMember = "Label";
            dllLabel.DataSource = connections;
        }
        #endregion

        #region Event Handlers
        private void btnOK_Click(object sender, System.EventArgs e)
        {
            btnOK.Enabled = false;
            pnlLog.Enabled = false;
            upd = new Updator(txtServer.Text,
                              txtUser.Text,
                              txtPass.Text,
                              txtDomain.Text,
                              ddlAuth.SelectedIndex,
                              txtInstance.Text);

            upd.Login();
            timer = new Timer
                        {
                            Interval = 500,
                            Enabled = true
                        };
            timer.Tick += timer_Tick;
            timer.Start();
            toolStripProgressBar1.Visible = true;
            toolStripStatusLabel1.Visible = true;
        }
        private void timer_Tick(object sender, System.EventArgs e)
        {
            if (upd.Finished)
            {
                timer.Stop();
                timer.Tick -= timer_Tick;
                toolStripProgressBar1.Visible = false;
                toolStripProgressBar1.Enabled = false;
                toolStripStatusLabel1.Visible = false;
                if (upd.Error)
                {
                    if (upd.Exception is SoapException)
                    {
                        MessageBox.Show("Something went wrong when communicating with the CRM web service: " +
                                        (upd.Exception as SoapException).Detail.InnerText, "Login", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    else
                    {
                        MessageBox.Show("Failed to login:\n" + upd.Exception.Message, "Login", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(dllLabel.Text))
                        dllLabel.Text = txtInstance.Text;
                    var conn = connections.SingleOrDefault(c => c.Label == dllLabel.Text);
                    if (conn == null)
                    {
                        conn = new Connection { Label = dllLabel.Text };
                        connections.Add(conn);
                    }
                    conn.UserName = txtUser.Text;
                    conn.Password = txtPass.Text;
                    conn.Domain = txtDomain.Text;
                    conn.Server = txtServer.Text;
                    conn.Instance = txtInstance.Text;
                    conn.Authentication = ddlAuth.SelectedIndex;
                    Connection.Save(connections);

                    var main = new frmMain
                                   {
                                       Updator = upd,
                                       Initiator = this
                                   };
                    main.Show();
                    Hide();
                }
                btnCancel.Enabled = true;
                btnOK.Enabled = true;
                pnlLog.Enabled = true;
            }
            else
            {
                toolStripStatusLabel1.Text = upd.Status;
            }
        }
        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            if (upd != null)
                upd.Abort();
            Application.Exit();
        }
        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (upd != null)
                upd.Abort();
        }
        private void dllLabel_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            var conn = (Connection)dllLabel.SelectedItem;
            txtUser.Text = conn.UserName;
            txtPass.Text = conn.Password;
            txtServer.Text = conn.Server;
            txtInstance.Text = conn.Instance;
            txtDomain.Text = conn.Domain;
            ddlAuth.SelectedIndex = conn.Authentication;
        }
        #endregion
    }
}
